package com.zhdl.modules.common.production.service;

import cn.hutool.core.util.HexUtil;
import cn.hutool.log.Log;
import com.github.xingshuangs.iot.protocol.s7.service.S7PLC;
import com.zhdl.hardware_contact.hardware_config.entity.ProjectConfiguration;
import com.zhdl.hardware_contact.hardware_config.service.dto.ProjectConfigQueryCriteria;
import com.zhdl.modules.common.production.entity.ProductionRecord;
import com.zhdl.modules.common.production.service.dto.ProductionReocrdQueryCriteria;
import com.zhdl.modules.common.production.service.impl.ProductionRecordServiceImpl;
import com.zhdl.modules.process.service.ProjectConfigProcessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class ProductionService {
    @Resource
    S7PLC s7PLC;
    @Resource
    ProjectConfigProcessService projectConfigProcessService;
    @Resource
    private ProductionRecordService productionRecordService;

     Map<String,Integer> productions = new LinkedHashMap<>();

    public static int dayProduction = 0;
    public static int allProduction = 0;

    //上电plc中的产量的值
    int originProduction;

    int lastProduction = -1;

    public void init(){
        List<Map<String,String>> all = productionRecordService.findByAll();

        for (Map<String, String> stringStringMap : all) {
            String k = stringStringMap.get("createDate");
            Object v = stringStringMap.get("productionOutput");
            log.info(k);
            log.info(v.toString());
            productions.put(k,Integer.parseInt(v.toString()));
        }


        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String createDate = formatter.format(date);
        if(Objects.isNull(productions.get(createDate))){
            productions.put(createDate,0);
        }


        allProductionTemp2 = 0;
        List<ProductionRecord> productionRecords = productionRecordService.findByCreateDateLike(createDate);
        int dayProductionTemp = 0;
        int allProductionTemp = 0;
        for (ProductionRecord record : productionRecords) {
            dayProductionTemp = dayProductionTemp + record.getProductionOutput();
        }
        productions.put(createDate,dayProductionTemp);

        productions.forEach((key, value)->{
            allProductionTemp2 = allProductionTemp2 + value;
        });
        allProductionTemp = allProductionTemp2;
        dayProduction = dayProductionTemp;
        allProduction = allProductionTemp;
        log.info("dayProduction<======>"+dayProduction);
        log.info("allProduction<======>"+allProduction);
    }
    int allProductionTemp2 = 0;
    int allProductionTemp1 = 0;
    public void updateProduction(String address, Integer count, ProjectConfiguration projectConfiguration){

        String Value = "";
        try {
            byte[] bytes = s7PLC.readByte(address,count);
            Value = HexUtil.encodeHexStr(bytes);
            log.info("DB2<===>"+Value);
            projectConfigProcessService.processProjectConfiguration(Value,projectConfiguration);
            log.info("<===>"+projectConfiguration.getValue());
        }catch (Exception e){
            System.out.println(e.getMessage());
        }

        int currentNumber = Integer.parseInt(projectConfiguration.getValue());
        if(lastProduction != currentNumber) {
            allProductionTemp1 = 0;


            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String createDate = formatter.format(date);
            log.info("createDate<==>"+createDate);
            ProductionRecord productionRecord = productionRecordService.findByCreateDateAndStatus(createDate, 1);
            if(currentNumber == 0){
                if(Objects.isNull(productionRecord)){
                    productionRecordService.updateStatusAll();
                }else {
                    if(productionRecord.getProductionOutput() != 0){
                        productionRecordService.updateStatusAll();
                        productionRecord = null;
                    }
                }
                originProduction = 0;
            }
            ProductionRecord pr = new ProductionRecord();
            if (Objects.isNull(productionRecord)) {
                log.info("productionRecord为null");
                pr.setStatus(1);
                pr.setProductionOutput(0);
                productionRecordService.insert(pr);
                originProduction = currentNumber;
                lastProduction = currentNumber;
            } else {
                //同一天断电重启的情况
                if(lastProduction == -1){
                    originProduction = currentNumber - productionRecord.getProductionOutput();
                }else {
                    productionRecordService.updateProductionById(productionRecord.getId(),currentNumber - originProduction);
                }
                lastProduction = currentNumber;
            }

            List<ProductionRecord> productionRecords = productionRecordService.findByCreateDateLike(createDate);
            int dayProductionTemp = 0;
            int allProductionTemp = 0;
            for (ProductionRecord record : productionRecords) {
                dayProductionTemp = dayProductionTemp + record.getProductionOutput();
            }
            productions.put(createDate,dayProductionTemp);

            productions.forEach((key, value)->{
                allProductionTemp1 = allProductionTemp1 + value;
            });
            allProductionTemp = allProductionTemp1;
            dayProduction = dayProductionTemp;
            allProduction = allProductionTemp;

        }
    }


    public Page<ProductionRecord> getProduction(ProductionReocrdQueryCriteria queryCriteria, Pageable pageable) {
        //获取内存
        List<ProductionRecord> Ram = new ArrayList<>();
        productions.forEach((k,v)->{
            if(queryCriteria.getCreateDate()==""||queryCriteria.getCreateDate().equals(k)) {
                ProductionRecord pr = new ProductionRecord();
                pr.setCreateDate(k);
                pr.setProductionOutput(v);
                Ram.add(pr);
            }
        });
        List<ProductionRecord> tempList = new ArrayList<>();
        //分页查询
        Integer hi = pageable.getPageNumber()*pageable.getPageSize()+pageable.getPageSize();
        if(hi>Ram.size()){
            hi = Ram.size();
        }
        for (int i=pageable.getPageNumber()*pageable.getPageSize();i<hi;i++){
            tempList.add(Ram.get(i));
        }


        Page<ProductionRecord> respPage = new PageImpl<>(tempList, pageable, Ram.size());
        return respPage;
    }
}


